import struct

class BinaryFile:

  def __init__(self, file):
    self.file = file

  def close(self):
    if hasattr(self.file, 'close'):
      self.file.close()

  def read(self, fmt, keys=None):
    length = struct.calcsize(fmt)
    values = struct.unpack(fmt, self.read_bytes(length))
    if len(values) > 1:
      if keys:
        return dict(zip(keys, list(values)))
      else:
        return list(values)
    else:
      return values[0]

  def read_bytes(self, length):
    return self.file.read(length)

  def read_string(self, length):
    ''' Reads length bytes from the stream, but checks for \0 termination characters. '''
    s = self.read_bytes(length)
    i = s.find('\0')
    if i == 0: return ''
    elif i == -1: return s
    else: return s[0:i]

  def seek(self, offset, whence=0):
    return self.file.seek(offset, whence)

  def tell(self):
    return self.file.tell()
